import UIKit
import CoreMotion

class LevelViewController: UIViewController {
    
    private let motionManager = CMMotionManager()
    private var levelView: LevelView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 初始化UI组件
        setupUI()
        
        // 启动加速度计更新
        if motionManager.isAccelerometerAvailable {
            motionManager.accelerometerUpdateInterval = 0.1 // 每0.1秒更新一次
            motionManager.startAccelerometerUpdates(to: .main) { [weak self] (data, error) in
                guard let accelerometerData = data else { return }
                self?.updateLevelFromAccelerometer(accelerometerData)
            }
        } else {
            print("Accelerometer is not available")
        }
    }
    
    private func setupUI() {
        // 创建并配置LevelView
        levelView = LevelView(frame: self.view.bounds)
        self.view.addSubview(levelView)
    }
    
    private func updateLevelFromAccelerometer(_ accelerometerData: CMAccelerometerData) {
        let acceleration = accelerometerData.acceleration
        
        // 计算X轴和Y轴的角度
        let roll = atan2(acceleration.x, sqrt(acceleration.y * acceleration.y + acceleration.z * acceleration.z))
        let pitch = atan2(acceleration.y, sqrt(acceleration.x * acceleration.x + acceleration.z * acceleration.z))
        
        // 将弧度转换为角度
        let rollDegrees = roll * 180 / .pi
        let pitchDegrees = pitch * 180 / .pi
        
        // 更新LevelView
        DispatchQueue.main.async {
            self.levelView.update(roll: rollDegrees, pitch: pitchDegrees)
        }
    }
    
    deinit {
        // 停止加速度计更新
        motionManager.stopAccelerometerUpdates()
    }
}

// 自定义LevelView类，用于绘制水平仪界面
class LevelView: UIView {
    
    private var roll: CGFloat = 0
    private var pitch: CGFloat = 0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    func update(roll: CGFloat, pitch: CGFloat) {
        self.roll = roll
        self.pitch = pitch
        setNeedsDisplay()
    }
    
    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else { return }
        
        // 设置背景颜色
        UIColor.white.setFill()
        context.fill(bounds)
        
        // 绘制中心圆圈
        let centerCircleRadius: CGFloat = min(bounds.width, bounds.height) / 6
        let centerPoint = CGPoint(x: bounds.midX, y: bounds.midY)
        context.setFillColor(UIColor.gray.cgColor)
        context.fillEllipse(in: CGRect(x: centerPoint.x - centerCircleRadius,
                                       y: centerPoint.y - centerCircleRadius,
                                       width: centerCircleRadius * 2,
                                       height: centerCircleRadius * 2))
        
        // 绘制指示器
        let indicatorLength: CGFloat = min(bounds.width, bounds.height) / 3
        context.setStrokeColor(UIColor.red.cgColor)
        context.setLineWidth(2)
        
        // X轴方向（roll）
        let rollEndPoint = CGPoint(x: centerPoint.x + cos(CGFloat(roll) * .pi / 180) * indicatorLength,
                                   y: centerPoint.y + sin(CGFloat(roll) * .pi / 180) * indicatorLength)
        context.move(to: centerPoint)
        context.addLine(to: rollEndPoint)
        context.strokePath()
        
        // Y轴方向（pitch）
        let pitchEndPoint = CGPoint(x: centerPoint.x + cos(CGFloat(pitch) * .pi / 180) * indicatorLength,
                                    y: centerPoint.y - sin(CGFloat(pitch) * .pi / 180) * indicatorLength)
        context.move(to: centerPoint)
        context.addLine(to: pitchEndPoint)
        context.strokePath()
        
        // 绘制文本标签
        let textAttributes: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 16),
            .foregroundColor: UIColor.black
        ]
        
        let rollText = String(format: "Roll: %.2f°", roll)
        let pitchText = String(format: "Pitch: %.2f°", pitch)
        
        rollText.draw(at: CGPoint(x: 20, y: 20), withAttributes: textAttributes)
        pitchText.draw(at: CGPoint(x: 20, y: 40), withAttributes: textAttributes)
    }
}
